package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkoauth2_1_0.models.GetAuthInfoHeaders;
import com.aliyun.dingtalkoauth2_1_0.models.GetAuthInfoRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAuthInfoResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiServiceGetAuthInfoRequest;
import com.dingtalk.api.response.OapiServiceGetAuthInfoResponse;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.CorpInfo;
import com.ruoyi.system.domain.invoice.CallbackBizData;
import com.ruoyi.system.service.ICorpInfoService;
import com.ruoyi.system.service.IDingCallbackService;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Service
public class DingCallbackService implements IDingCallbackService {
    @Autowired
    private ICorpInfoService corpInfoService;

    @Autowired
    private CorpTokenService corpTokenService;

    /**
     * 分析推送类型
     *
     * @param plainText
     */
    @Override
    public void checkPushPlainText(String plainText) {

        JSONObject obj = JSON.parseObject(plainText);
        JSONArray bizArray = obj.getJSONArray("bizData");
        CallbackBizData callbackBizData = bizArray.getObject(0, CallbackBizData.class);
        if (callbackBizData.getBiz_type() == 2) {
            processSuiteTicket(callbackBizData);
        }
        if (callbackBizData.getBiz_type() == 4) {
            processCorpAuthInfo(callbackBizData);

        }
        if (callbackBizData.getBiz_type() == 7) {

        }
    }

    private void processCorpAuthInfo(CallbackBizData callbackBizData) {
        JSONObject bizData = JSON.parseObject(callbackBizData.getBiz_data());
        String syncAction = bizData.getString("syncAction");
        if ("org_suite_auth".equals(syncAction) || "org_suite_change".equals(syncAction)) {
            JSONObject auth_corp_info = bizData.getJSONObject("auth_corp_info");
            String corpName = auth_corp_info.getString("corp_name");
            JSONObject auth_info = bizData.getJSONObject("auth_info");
            JSONArray agentList = auth_corp_info.getJSONArray("agent");
//                for (Object aobj : agentList) {
//                    JSONObject tAgent = JSONObject.parseObject(JSONObject.toJSONString(aobj));
//                    if (tAgent.getString(agentid))
//                }

            JSONObject tAgent = agentList.getJSONObject(0);
            Long agentId = tAgent.getLong("agentid");

            CorpInfo corpInfo = corpInfoService.selectCorpInfoById(callbackBizData.getCorp_id());
            if (corpInfo == null) {
                corpInfo = new CorpInfo();
                corpInfo.setId(callbackBizData.getCorp_id());
                corpInfo.setCorpId(callbackBizData.getCorp_id());
                corpInfo.setAgentId(agentId);
                corpInfo.setCorpName(corpName);
                corpInfoService.insertCorpInfo(corpInfo);
            } else {
                corpInfo.setAgentId(agentId);
                corpInfo.setCorpName(corpName);
                corpInfoService.updateCorpInfo(corpInfo);
            }
        }
    }

    /**
     * 处理推送suiteTicket
     *
     * @param callbackBizData
     */
    @Override
    public void processSuiteTicket(CallbackBizData callbackBizData) {
//        {
//            "EventType": "SYNC_HTTP_PUSH_HIGH",
//                "bizData": [
//            {
//                "gmt_create": 1652841516000,
//                    "biz_type": 2,
//                    "open_cursor": 0,
//                    "subscribe_id": "253***1_0",
//                    "id": 230**,
//                "gmt_modified": 1652841516000,
//                    "biz_id": "253****1",
//                    "biz_data": "{\"syncAction\":\"suite_ticket\",\"suiteTicket\":\"3Je*************ZtZa4sdl9do4dWC********ykDelR5AdPZt02lhkOY3p7yLKkdN9nVktPIkmlIjn2A\",\"syncSeq\":\"1ABA5C5215CB8BDEE8CA8D33A9\"}",
//                    "corp_id": "ding9f50b1*********",
//                    "status": 0
//            }
//  ]
//        }
        JSONObject bizData = JSON.parseObject(callbackBizData.getBiz_data());
        String syncAction = bizData.getString("syncAction");
        if ("suite_ticket".equals(syncAction)) {
            String suiteTicket = bizData.getString("suiteTicket");
            CorpInfo corpInfo = corpInfoService.selectCorpInfoById(callbackBizData.getCorp_id());
            if (corpInfo == null) {
                corpInfo = new CorpInfo();
                corpInfo.setId(callbackBizData.getCorp_id());
                corpInfo.setCorpId(callbackBizData.getCorp_id());
                corpInfo.setSuiteTicket(suiteTicket);
                corpInfoService.insertCorpInfo(corpInfo);
            } else {
                corpInfo.setSuiteTicket(suiteTicket);
                corpInfoService.updateCorpInfo(corpInfo);
            }
            if (corpInfo.getAgentId() == null) {
                checkCorpAuthInfo(corpInfo);
            }
        }
    }

    public static com.aliyun.dingtalkoauth2_1_0.Client createClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }

//    private void callbackAgentId(CorpInfo corpInfo) {
//        try {
//            com.aliyun.dingtalkoauth2_1_0.Client client = createClient();
//            GetAuthInfoHeaders getAuthInfoHeaders = new GetAuthInfoHeaders();
//            getAuthInfoHeaders.xAcsDingtalkAccessToken = corpTokenService.getCorpToken(corpInfo.getCorpId());
//            GetAuthInfoRequest getAuthInfoRequest = new GetAuthInfoRequest()
//                    .setAuthCorpId(corpInfo.getCorpId());
//
//            GetAuthInfoResponse authInfoResponse = client.getAuthInfoWithOptions(getAuthInfoRequest, getAuthInfoHeaders, new RuntimeOptions());
//            System.out.println(JSONObject.toJSONString(authInfoResponse.body));
//        } catch (TeaException err) {
//            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
//                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                err.printStackTrace();
//            }
//
//        } catch (Exception _err) {
//            TeaException err = new TeaException(_err.getMessage(), _err);
//            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
//                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                _err.printStackTrace();
//            }
//
//        }
//
//    }


    public void checkCorpAuthInfo(CorpInfo corpInfo) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/service/get_auth_info");
        OapiServiceGetAuthInfoRequest req = new OapiServiceGetAuthInfoRequest();
        req.setSuiteKey("suitetkbvy8k3rgehem0a");
        req.setAuthCorpid(corpInfo.getCorpId());
// 第三方企业应用的填写应用SuiteKey和SuiteSecret。
// 定制应用填写应用的CustomKey和CustomSecret。
        OapiServiceGetAuthInfoResponse rsp = null;
        try {
            rsp = client.execute(req, "suitetkbvy8k3rgehem0a", "2IFUGZVtQmZ59ZyVipTFaosDeh-pgIKzKA-221UvgQzeofTyFkLXt4ydMHVatAtN", corpInfo.getSuiteTicket());
        } catch (ApiException e) {
            throw new RuntimeException(e);
        }

        if (rsp.isSuccess()) {
            OapiServiceGetAuthInfoResponse.AuthCorpInfo authCorpInfo = rsp.getAuthCorpInfo();
            corpInfo.setCorpName(authCorpInfo.getCorpName());
            OapiServiceGetAuthInfoResponse.AuthInfo authInfo = rsp.getAuthInfo();
            List<OapiServiceGetAuthInfoResponse.Agent> agentList = authInfo.getAgent();
            Optional<OapiServiceGetAuthInfoResponse.Agent> okAgent = agentList.stream().filter(agent -> agent.getAppid() == 130653L).findFirst();
            if (okAgent.isPresent()) {
                corpInfo.setAgentId(okAgent.get().getAgentid());
                corpInfoService.updateCorpInfo(corpInfo);
            }
        }
        System.out.println(JSON.toJSONString(rsp));
    }
}
